<?php
/**
 * @package Admin
 * @author Henrique Droog <henridroog@gmail.com>
 * @name RoleMapper
 * @since 19/03/2011
 * @version 1.0
 */
class Admin_Model_RoleMapper {

    protected $_dbTable;

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Admin_Model_DbTable_Role');
        }
        return $this->_dbTable;
    }

    public function save(Admin_Model_Role $role) {
        $data = array(
            'role_name' => $role->getName(),
        );
//        if ($role->getId()<=0)
//                $role->setId ("NULL");
        //if (null === ($id = $role->getId())) {
        if ($role->getId()<=0) {
            unset($data['role_id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('role_id = ?' => $role->getId()));
        }
    }

    public function find($id, Admin_Model_Role $role) {
        $result = $this->getDbTable()->find($id['id']);
//        echo "<pre> Find:";
//        print_r($result);
//        echo "</pre>";
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $role->setId($row->role_id)
                  ->setName($row->role_name);
        return $role;
    }

    public function fetchAll() {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Admin_Model_Role();
            $entry->setId($row->role_id)
                    ->setName($row->role_name);
            $entries[] = $entry;
        }
        return $entries;
    }
    //
    public function del(Admin_Model_Role $role){
        $where = array("role_id = ?" =>$role->getId());
        $resultSet = $this->getDbTable()->delete($where);
        return $resultSet;
    }

}